package com.syezon.wifikey.speed;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;

public class SpeedTestUtils {

    private static final String TAG = SpeedTestUtils.class.getSimpleName();

    public static int getDnsDelay(String domain) {
        int delay = 0;
        long startTime = System.currentTimeMillis();
        try {
            InetAddress inetAddress = InetAddress.getByName(domain);
            long endTime = System.currentTimeMillis();
            delay = (int) (endTime - startTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return delay;
    }

    public static int getNetDelay(String domain) {
        int delay = 0;
        try {
            Process p = Runtime.getRuntime().exec("ping -c 3 " + domain);//ping百度
            BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str = "";
            String temp = null;
            while ((str = buf.readLine()) != null) {
                if (str.contains("avg")) {
                    temp = str;
                    break;
                }
            }
            if (temp != null) {
                int i = temp.indexOf("/", 20);
                int j = temp.indexOf(".", i);
                delay = Integer.parseInt(temp.substring(i + 1, j));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return delay;
    }

    /**
     * 下载文件测试网速
     */
    public static int getSpeed(String urlPath) {
        URL url;
        InputStream inputStream = null;
        BufferedWriter bufferedWriter = null;
        Socket socket = null;
        int avgSpeed = 0;
        try {
            url = new URL(urlPath);
            String host = url.getHost();
            int port = 80;
            SocketAddress socketAddress = new InetSocketAddress(host, port);
            socket = new Socket();
            socket.connect(socketAddress, 5000);
            socket.setReceiveBufferSize(4096000);
            socket.setSoTimeout(5000);
            OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
            bufferedWriter = new BufferedWriter(streamWriter);
            bufferedWriter.write("GET " + urlPath + " HTTP/1.1\r\n");
            bufferedWriter.write("Host: " + host + "\r\n");
            bufferedWriter.write("Connection: close \r\n");
            bufferedWriter.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0 \r\n");
            bufferedWriter.write("\r\n");
            bufferedWriter.flush();
            inputStream = socket.getInputStream();
            byte[] b = new byte[10240];
            int readCount = 0;
            long tmpBytes = 0;
            int readTimes = 0;
            long startTime = System.currentTimeMillis();
            while ((readCount = inputStream.read(b)) != -1) {
                long now = System.currentTimeMillis();
                readTimes++;
                tmpBytes += readCount;
                if (tmpBytes >= 102400 || readTimes > 20) {
                    break;
                }
                if ((now - startTime) / 1000 > 10) {
                    //测试总时间不能超过10s
                    break;
                }
            }
            long intervalTime = System.currentTimeMillis() - startTime;
            avgSpeed = (int) (tmpBytes / intervalTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return avgSpeed;
    }

    /**
     * 下载文件测试网速
     */
    public static SpeedInfo getSpeedInfo(String urlPath) {
        SpeedInfo speedInfo = new SpeedInfo();
        URL url;
        InputStream inputStream = null;
        BufferedWriter bufferedWriter = null;
        Socket socket = null;
        int avgSpeed = 0;
        int maxSpeed = 0;
        try {
            url = new URL(urlPath);
            String host = url.getHost();
            int port = 80;
            SocketAddress socketAddress = new InetSocketAddress(host, port);
            socket = new Socket();
            socket.connect(socketAddress, 5000);
            socket.setReceiveBufferSize(4096000);
            socket.setSoTimeout(5000);
            OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
            bufferedWriter = new BufferedWriter(streamWriter);
            bufferedWriter.write("GET " + urlPath + " HTTP/1.1\r\n");
            bufferedWriter.write("Host: " + host + "\r\n");
            bufferedWriter.write("Connection: close \r\n");
            bufferedWriter.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0 \r\n");
            bufferedWriter.write("\r\n");
            bufferedWriter.flush();
            inputStream = socket.getInputStream();
            byte[] b = new byte[10240];
            int readCount = 0;
            long tmpBytes = 0;
            int readTimes = 0;
            long startTime = System.currentTimeMillis();
            while ((readCount = inputStream.read(b)) != -1) {
                long now = System.currentTimeMillis();
                readTimes++;
                tmpBytes += readCount;
                if (tmpBytes >= 102400 || readTimes > 20) {
                    break;
                }
                if ((now - startTime) / 1000 > 10) {
                    //测试总时间不能超过10s
                    break;
                }
            }
            long intervalTime = System.currentTimeMillis() - startTime;
            avgSpeed = (int) (tmpBytes / intervalTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return speedInfo;
    }

    public static class SpeedInfo{
        public int avgSpeed;
        public int maxSpeed;
    }
}
